package com.raymond.client.netty;

import com.alibaba.fastjson.JSONObject;
import com.raymond.client.codec.ICodec;
import com.raymond.client.msg.BaseAgreement;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 消息解码
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-14 10:19
 */
@ChannelHandler.Sharable
public class MsgDecoder extends MessageToMessageDecoder<BaseAgreement> {

    private final static Logger logger = LoggerFactory.getLogger(MsgDecoder.class);

    private ICodec codec;

    public MsgDecoder(ICodec codec) {
        this.codec = codec;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, BaseAgreement msg, List<Object> out) {
        try {
            codec.getBaseDecoder(msg.getCommandId()).decode(ctx, msg, out);
        } catch (Exception e) {
            logger.error("消息解码异常,commandId:{}, msg:{}", msg.getCommandId(), JSONObject.toJSONString(msg), e);
//            if (msg.getCommandId() > 0) {
//                ctx.writeAndFlush(new ExceptionResponse(msg.getSequenceId(), 4));
//            }
        }
    }
}
